<template>
  <view class="square-page">
    <view class="square-box">
      <!-- 内容 -->
      <view class="square-content">
        <!-- 榜单切换 -->
        <view class="square-category-tabs">
          <view
            class="square-category-tabs-item"
            v-for="(item, index) in categorylist"
            :key="index"
            @click="changeCategory(index)"
            :class="{
              'square-tab-item': true,
              'square-tab-active': currentCategory === index,
            }"
          >
            {{ item }}
          </view>
        </view>
        <!-- 搜索 -->
        <view class="square-bar">
          <uni-search-bar
            title="搜索"
            @confirm="search"
            @input="input"
          ></uni-search-bar>
        </view>
        <!-- 内容瀑布流 -->
        <view class="square-content-list">
          <custom-waterfalls-flow :value="musicList.list" :column="column" :key="currentCategory">
            <template v-slot:default="item">
              <view class="card-item" @click="showDetail(item)">
                <view class="card-item-info">
                  <view class="card-title">{{ item.title }}</view>
                  <view class="card-author">{{ item.artist }}</view>
                  <view class="card-meta">
                    <view class="card-create-time">{{ item.createTime }}</view>
                    <view class="card-stats">
                      <view class="card-play-count">
                        <uni-icons
                          type="play"
                          size="20rpx"
                          color="#999"
                          class="card-stat-icon"
                        ></uni-icons>
                        {{ formatNum(item.playCount) }}
                      </view>
                      <view class="card-like-count">
                        <uni-icons
                          type="heart"
                          size="20rpx"
                          color="#999"
                          class="card-stat-icon"
                        ></uni-icons>
                        {{ formatNum(item.likeCount) }}
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </template>
          </custom-waterfalls-flow>
        </view>
      </view>
    </view>
    <!-- 单个卡片详情弹窗 -->
    <view v-if="showDetailModal" class="card-detail-modal">
      <view class="card-detail-mask" @click="hideDetail" :class="{'mask-enter': modalAnimation === 'modal-enter', 'mask-leave': modalAnimation === 'modal-leave'}"></view>

      <view class="card-detail-content" :class="{'content-enter': modalAnimation === 'modal-enter', 'content-leave': modalAnimation === 'modal-leave', 'content-transition': true}">
        <image :src="currentDetail.image" mode="aspectFit" class="detail-image" :class="{'image-loaded': modalAnimation === 'modal-enter'}"></image>

        <view class="card-detail-title animate-item" :style="{ animationDelay: '300ms' }">{{ currentDetail.title }}</view>
        <view class="card-detail-author animate-item" :style="{ animationDelay: '450ms' }">{{ currentDetail.artist }}</view>

        <view class="card-detail-meta animate-item" :style="{ animationDelay: '600ms' }">
          <view class="card-detail-create-time">{{ currentDetail.createTime }}</view>
          <view class="card-detail-stats">
            <view class="card-detail-play-count">播放: {{ formatNum(currentDetail.playCount) }}</view>
            <view class="card-detail-like-count">点赞: {{ formatNum(currentDetail.likeCount) }}</view>
          </view>
        </view>

        <view class="card-detail-action-bar animate-item" :style="{ animationDelay: '750ms' }">
          <view class="card-detail-action-btn" @click.stop="handleComment(currentDetail)"><uni-icons type="chatbubble" size="28" color="#3cc88c"></uni-icons></view>
          <view class="card-detail-action-btn" @click="handleCollect(currentDetail)"><uni-icons type="star" size="28" color="#3cc88c"></uni-icons></view>
          <view class="card-detail-goBtn" @click="toPlay()"> 播放页 </view>
          <view class="card-detail-action-btn" @click="handleShare(currentDetail)"><uni-icons type="redo" size="28" color="#3cc88c"></uni-icons></view>
          <view class="card-detail-action-btn" @click="handlePlay(currentDetail)"><image class="card-detail-image-icon" :src="!ifPlay ? '/static/icons/play-green.svg' : '/static/icons/pause-green.svg'" :class="{'card-detail-rotate-animation': ifPlay}" mode=""></image></view>
        </view>
      </view>
    </view>

    <!-- 评论区组件 -->
    <CommentComponent
      :showComment="showComment"
      :commentData="commentData"
      :currentCommentMusicId="currentCommentMusicId"
      @hideCommentEvent="hideComment"
    />
  </view>
</template>

<script setup>
import { ref, reactive, watch, onMounted, onUnmounted } from "vue"
import CommentComponent from "/components/CommentComponent.vue"

const ifPlay = ref(false)
// 瀑布列数
const column = ref(2)
// 榜单分类
const categorylist = ref(["热门榜单", "新生榜单", "随机漫游"])
const currentCategory = ref(0)
// 单个卡片详情弹窗显示状态
const showDetailModal = ref(false)
// 当前显示详情的音乐数据
const currentDetail = ref({})
// 添加动画状态控制
const modalAnimation = ref("")

// 评论区相关状态
const showComment = ref(false)
const currentCommentMusicId = ref(null)

// 评论数据
const commentData = reactive({
  list: [
    {
      musicId: 1,
      comments: [
        {
          id: 101,
          userName: "音乐爱好者",
          content: "这首曲子太好听了，循环播放中~",
          time: "2024-05-15 14:30"
        },
        {
          id: 102,
          userName: "钢琴迷",
          content: "钢琴旋律很动人，有种治愈的感觉",
          time: "2024-05-16 09:15"
        }
      ]
    },
    {
      musicId: 2,
      comments: [
        {
          id: 201,
          userName: "夏日控",
          content: "很有夏日的感觉，一听就心情愉悦",
          time: "2024-06-22 16:45"
        }
      ]
    }
  ]
})

// 监听弹窗显示状态变化，触发动画
watch(showDetailModal, (newVal) => {
  if (newVal) {
    // 显示弹窗时添加进入动画类
    setTimeout(() => {
      modalAnimation.value = "modal-enter"
    }, 10)
  } else {
    // 隐藏弹窗时添加离开动画类
    modalAnimation.value = "modal-leave"
    // 动画结束后清除类名
    setTimeout(() => {
      modalAnimation.value = ""
    }, 350)
  }
})

// 数字格式化方法（1234→1.2k，12345→1.2w）
const formatNum = (num) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + "w"
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + "k"
  }
  return num
}

// 切换榜单分类
const changeCategory = (index) => {
  currentCategory.value = index;
  switch (index) {
  case 0:
    fetchMusicList('hot');
    break;
  case 1:
    fetchMusicList('new');
    break;
  case 2:
    fetchMusicList('random');
    break;
  default:
    fetchMusicList('hot');
  }
}
// 显示单个卡片详情弹窗
const showDetail = (item) => {
  currentDetail.value = item
  showDetailModal.value = true
}

// 隐藏单个卡片详情弹窗
const hideDetail = () => {
  showDetailModal.value = false
}

// 播放/暂停音乐
const handlePlay = (item) => {
  ifPlay.value = !ifPlay.value // 切换播放状态
  if (ifPlay.value) {
    console.log("播放音乐:", item.title)
  } else {
    console.log("暂停音乐:", item.title)
  }
}

const handleCollect = (item) => {
  console.log("收藏音乐:", item.title)
  // 收藏逻辑实现
}

const handleShare = (item) => {
  console.log("分享音乐:", item.title)
  // 分享逻辑实现
}

// 显示评论区（仅保留一个定义）
const handleComment = (item) => {
  currentCommentMusicId.value = item.id
  showComment.value = true
}

// 隐藏评论区
const hideComment = () => {
  showComment.value = false
}

const toPlay = () => {
  uni.navigateTo({
    url: "/pages/play/play"
  })
}

// 榜单数据缓存对象
const musicCache = reactive({})

const musicList = reactive({
  list: []
})

// 获取榜单数据
const fetchMusicList = async (type) => {
  // 检查缓存，存在则直接使用
  if (musicCache[type]) {
    musicList.list = musicCache[type]
    return
  }
  try {
    const response = await uni.request({
      url: `/api/music/${type}`,
      method: 'GET'
    }); 
    if (response.data.code === 200) {
      musicList.list = response.data.data.list
    // 存入缓存
    musicCache[type] = response.data.data.list
    }
  } catch (error) {
    console.error('获取榜单数据失败:', error)
  }
}

// 初始化加载热门榜单
onMounted(() => {
  fetchMusicList('hot');
})

// 离开页面时清除缓存
onUnmounted(() => {
  Object.keys(musicCache).forEach(key => {
    delete musicCache[key]
  })
})

// 搜索相关方法
const search = (value) => {
  console.log("搜索内容:", value)
  // 实现搜索逻辑
}

const input = (value) => {
  console.log("输入内容:", value)
  // 实现输入实时处理逻辑
}
</script>

<style lang="scss">
// 广场页面基础样式
.square-page {
  box-sizing: border-box;
  // background-color: #f5f7fa;

  .square-box {
    .square-content {
      padding: 20rpx;

      // 广场页面的分类标签样式
      .square-category-tabs {
        display: flex;
        padding: 0 30rpx;
        margin-bottom: 15rpx;

        .square-tab-item {
          flex: 1;
          text-align: center;
          padding: 25rpx 0;
          color: #666;
          position: relative;
          font-size: 30rpx;
          transition: color 0.3s ease;
        }

        .square-tab-item.square-tab-active {
          color: #3cc88c;
          font-weight: 500;
        }

        .square-tab-item.square-tab-active::after {
          content: "";
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 40%;
          height: 4rpx;
          background-color: #3cc88c;
          border-radius: 2rpx;
          transition: width 0.3s ease;
        }

        .square-tab-item:not(.square-tab-active):hover {
          color: #999;
        }
      }

      // 搜索框样式
      .square-bar {
        margin-bottom: 15rpx;
      }

      // 广场页面的瀑布流列表容器样式
      .square-content-list {
        column-gap: 20rpx;
      }
    }
  }
}

// 列表中的单个卡片样式
.card-item {
  padding: 0;
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  transition: all 0.3s ease;
  break-inside: avoid;

  .card-item-img-wrap {
    position: relative;
    width: 100%;
    padding-top: 75%;
    overflow: hidden;
  }

  .card-item-img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    transition: transform 0.5s ease;
  }

  .card-play-icon-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(transparent, rgba(0, 0, 0, 0.2));
    opacity: 0;
    transition: opacity 0.3s ease;
    display: flex;
    align-items: flex-end;
    justify-content: flex-end;
    padding: 20rpx;
  }

  .card-play-icon {
    background: #3cc88c;
    border-radius: 50%;
    padding: 10rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
    transform: scale(0.9);
    transition: transform 0.3s ease;
  }

  .card-item-img-wrap:hover {
    .card-play-icon-mask {
      opacity: 1;
    }
    .card-item-img {
      transform: scale(1.03);
    }
    .card-play-icon {
      transform: scale(1);
    }
  }

  .card-item-info {
    padding: 24rpx 20rpx;
  }

  .card-title {
    font-size: 34rpx;
    font-weight: 600;
    color: #1a1a1a;
    margin-bottom: 12rpx;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .card-author {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 18rpx;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .card-meta {
    display: flex; // 时间与统计信息左右分布
    justify-content: space-between;
    align-items: center;
    font-size: 24rpx;
  }

  .card-create-time {
    color: #999; // 浅灰色，弱化次要信息
  }

  .card-stats {
    display: flex;
    gap: 24rpx; // 增加统计项间距
  }

  .card-play-count,
  .card-like-count {
    display: flex;
    align-items: center;
    color: #888;
    gap: 6rpx; // 图标与数字间距
  }

  .card-stat-icon {
    vertical-align: middle;
  }

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  }
}

// 卡片详情弹窗样式
.card-detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
  overflow: hidden;
}

// 遮罩层动画
.card-detail-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0);
  backdrop-filter: blur(0);
  transition: all 0.35s ease;
}

.mask-enter {
  background-color: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(5rpx);
}

.mask-leave {
  background-color: rgba(0, 0, 0, 0);
  backdrop-filter: blur(0);
}

// 弹窗内容动画
.card-detail-content {
  position: relative;
  width: 80%;
  max-width: 600rpx;
  border-radius: 32rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
  background: #fff;
  // overflow-y: auto;
  opacity: 0;
  transform: scale(0.85);
}

.content-transition {
  transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

.content-enter {
  opacity: 1;
  transform: scale(1);
}

.content-leave {
  opacity: 0;
  transform: scale(0.85);
}

// 图片延迟显示动画
.detail-image {
  width: 100%;
  height: 700rpx;
  margin: 15rpx 0 25rpx;
  opacity: 0;
  transform: translateY(20rpx);
  transition: all 0.5s ease 0.2s;
}

.image-loaded {
  opacity: 1;
  transform: translateY(0);
}

// 内容元素依次上移动画
.animate-item {
  opacity: 0;
  transform: translateY(30rpx);
  animation-fill-mode: forwards;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.card-detail-title,
.card-detail-author,
.card-detail-meta,
.card-detail-action-bar {
  animation: slideUp 0.4s ease forwards;
}

// 弹窗内容样式
.card-detail-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 15rpx;
  color: #1a1a1a;
}

.card-detail-author {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1px solid #f5f5f5;
}

.card-detail-meta {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 30rpx;
  line-height: 1.6;
}

.card-detail-stats {
  display: flex;
  gap: 25rpx;
  margin-top: 10rpx;
}

// 卡片详情弹窗的操作栏样式
.card-detail-action-bar {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 20rpx 0;
  border-radius: 12rpx;
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(10rpx);
  margin-top: 20rpx;
}

.card-detail-action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 70rpx;
  height: 70rpx;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.8);
  transition: all 0.2s ease;
  position: relative;

  .card-detail-image-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 90%;
    height: 100%;
    border-radius: 50%;
    transition: all 0.3s ease;
  }
}

.card-detail-action-btn:active {
    transform: scale(0.95);
    background-color: rgba(255, 255, 255, 1);
}

.card-detail-goBtn {
  padding: 12rpx 20rpx;
  color: #3cc88c;
  border-bottom: 1rpx solid #3cc88c;
}

// 卡片详情的播放动画
.card-detail-rotate-animation {
  animation: card-rotate 5s linear infinite;
}

@keyframes card-rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>